package com.wbao.dianniu.ui;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Xml;
import android.webkit.WebResourceRequest;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.permissionutil.PermissionListener;
import com.permissionutil.PermissionUtil;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;


import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yejianjun on 2018/1/29.
 */

public abstract class MapBaseActivity extends BaseFragmentActivity {


    public abstract void receiveLocation(BDLocation location);
    private boolean locPermission = false;

    private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener() {
    };

    public boolean getLocPermission(){
        return locPermission;
    }

    public void initLocation() {

        if(Build.VERSION.SDK_INT < 23){
            locPermission = true;
            mLocationClient = new LocationClient(MapBaseActivity.this);
            mLocationClient.registerLocationListener(myListener);
            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(1000);
            option.setIsNeedAddress(true);
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        }else{
            PermissionUtil permissionUtil = new PermissionUtil(MapBaseActivity.this);
            permissionUtil.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION/*, Manifest.permission.ACCESS_WIFI_STATE*/},
                    new PermissionListener() {
                        @Override
                        public void onGranted() {
                            try {
                                // 定位初始化
                                mLocationClient = new LocationClient(MapBaseActivity.this);
                                mLocationClient.registerLocationListener(myListener);
                                LocationClientOption option = new LocationClientOption();
                                option.setOpenGps(true); // 打开gps
                                option.setCoorType("bd09ll"); // 设置坐标类型
                                option.setScanSpan(1000);
                                option.setIsNeedAddress(true);
                                mLocationClient.setLocOption(option);
                                mLocationClient.startIndoorMode();
                                mLocationClient.start();
                                locPermission = true;
                            } catch (Exception e) {
                                locPermission = false;
                                PermissionUtils.getInstance().showMsg(MapBaseActivity.this, "权限被拒绝，此功能不能正常使用，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                            }
                        }

                        @Override
                        public void onDenied(List<String> list) {
                            locPermission = false;
                            //Toast第一个被拒绝的权限
                            //showMsg("您拒绝权限申请，此功能将不能正常使用，您可以去设置页面重新授权");
                            showMsg(MapBaseActivity.this, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                        }

                        @Override
                        public void onShouldShowRationale(List<String> list) {
                            locPermission = false;
                            //Toast第一个勾选不在提示的权限
                            showMsg(MapBaseActivity.this, "权限被拒绝，此功能不能正常使用。\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                        }
                    });
        }

        /*Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE).build(), new AcpListener() {
            @Override
            public void onGranted() {
                // 定位初始化
                mLocationClient = new LocationClient(MapBaseActivity.this);
                mLocationClient.registerLocationListener(myListener);
                LocationClientOption option = new LocationClientOption();
                option.setOpenGps(true); // 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
                mLocationClient.start();

//                Notification.toast(MapActivity.this, "权限允许");
            }

            @Override
            public void onDenied(List<String> permissions) {
//                Notification.toast(MapActivity.this, permissions.toString() + "权限拒绝");
            }
        });*/

    }

    public void showMsg(final Activity activity, String msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        builder.setMessage(msg);
        builder.setTitleVisbily(false);
        builder.setPositiveButton("设置权限", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                goToAppSetting(activity);
            }
        });
        builder.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    /**
     * 打开Setting
     */
    private void goToAppSetting(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", "com.wbao.dianniu", null);
        intent.setData(uri);
        activity.startActivityForResult(intent, 123);
    }


    private class MyLocationListener implements BDLocationListener {

        public MyLocationListener() {

        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }
            if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation || location.getLocType() == BDLocation.TypeOffLineLocation) {// GPS定位结果
                receiveLocation(location);
                getLocation(location.getLatitude()+"",location.getLongitude()+"");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeServerError) {
//                Log.e("Location","服务端网络定位失败.......");
                Notification.toast(MapBaseActivity.this, "服务端网络定位失败");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                Log.e("Location","网络不同导致定位失败，请检查网络是否通畅");
                Notification.toast(MapBaseActivity.this, "网络不同导致定位失败，请检查网络是否通畅");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                Notification.toast(MapBaseActivity.this, "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//                Log.e("Location","无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                mLocationClient.stop();
            }
        }

//        @Override
//        public void onConnectHotSpotMessage(String s, int i) {
//
//        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 退出时销毁定位
        if (null != mLocationClient) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
        }
    }

    @Override
    protected void onStop() {
        if (null != mLocationClient) {
            mLocationClient.stop();
        }
        super.onStop();
    }


    public void getLocation(final String longitude,final String latitude){
        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader bufferedReader = null;
                try {
                    String mCode="07:2C:CF:83:5D:53:BF:C2:BA:0C:FE:7E:0C:E0:5A:64:09:82:59:3C;com.wbao.dianniu"; //这里填写申请ak时用的安全码
                    String key = "xGMyZae2GECduihNV3FDTF3gchrGBECl";
                   // http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=39.934,116.329&output=json&pois=1&ak=您的ak //GET请求
                    String path="http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location="+longitude+","
                            +latitude+"&output="+"json"+"&pois=1&ak="+key+"&mcode="+mCode;
                    URL url=new URL(path);
                    URLConnection connection=url.openConnection();
                    connection.setConnectTimeout(2000);
                    connection.connect();
                    bufferedReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder stringBuilder=new StringBuilder();
                    String line=null;
                    while((line=bufferedReader.readLine())!=null){
                        stringBuilder.append(line);
                    }
//                    String info=stringBuilder.toString();
                    setLocation(stringBuilder.toString());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                finally {
                    try{
                        if(bufferedReader!=null){
                            bufferedReader.close();
                        }
                    }
                    catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void setLocation(String info){

    }




}
